package com.kushe.site.controller;

import com.kushe.dao.*;
import com.kushe.entity.*;
import com.kushe.site.form.OrderForm;
import com.kushe.util.KSController;
import com.kushe.util.core.DaoFactory;
import org.nutz.dao.QueryResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WhiteBlue on 15/4/2.
 */
@org.springframework.stereotype.Controller
@RequestMapping(value = "/design")
public class DesignController extends KSController {

    /**
     * 进入single界面
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public Object index(@RequestParam(value = "design", required = true) int design_id,
                        @RequestParam(value = "page", required = false, defaultValue = "1") int page, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        DesignDao designDao = DaoFactory.getDao(DesignDao.class);
        OrderDao orderDao = DaoFactory.getDao(OrderDao.class);


        Design design = designDao.get(design_id);
        if (design == null) {
            return this.renderError(404, response);
        } else {
            User user = (User) request.getSession().getAttribute("user");
            if (user != null) {
                if (designDao.isCollected(design_id, user.getId())) {
                    this.setAttr("isCollected", true);
                } else {
                    this.setAttr("isCollected", false);
                }
            }
            this.setAttr("design", design);
            this.setAttr("user", DaoFactory.getDao(UserDao.class).get(design.getUser_id()));
            this.setAttr("page", designDao.getPostList(design_id, page));
            this.setAttr("user_buy", orderDao.getForDesign(design_id));

            this.setAttr("actionUrl", "/design?design=" + design_id + "&page=");
            return this.render("/design/single.html");
        }
    }


    /**
     * 进入商品界面
     */
    @RequestMapping(value = "info", method = RequestMethod.GET)
    public Object info(@RequestParam(value = "design", required = true) int designId, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        DesignDao designDao = DaoFactory.getDao(DesignDao.class);

        Design design = designDao.get(designId);
        if (design == null) {
            return this.renderError(404, response);
        } else {
            User user = (User) request.getSession().getAttribute("user");
            Order order = DaoFactory.getDao(OrderDao.class).getForMe(designId, user.getId());
            if (order != null) {
                this.setAttr("order", order);
            }
            this.setAttr("design", design);
            this.setAttr("user", DaoFactory.getDao(UserDao.class).get(design.getUser_id()));
            this.setAttr("news", designDao.getHotForIndex());
            return this.render("/design/info.html");
        }
    }


    @RequestMapping(value = "listBySort", method = RequestMethod.GET)
    public Object listBySort(@RequestParam(value = "sort", required = true) int sortId, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        SortDao sortDao = DaoFactory.getDao(SortDao.class);
        Sort sort = sortDao.get(sortId);
        if (sort == null) {
            return this.renderError(404, response);
        } else {
            sortDao.addPV(sort);
            Category category = sort.getCategory();
            QueryResult qr = DaoFactory.getDao(DesignDao.class).getBySort(1, sortId);
            this.setAttr("sort", sort);
            this.setAttr("category", category);
            this.setAttr("list", qr.getList());
            return this.render("/design/listBySort.html");
        }
    }


    @RequestMapping(value = "listByCategory", method = RequestMethod.GET)
    public Object listByCategory(@RequestParam(value = "category", required = true) int categoryId, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        Category category = DaoFactory.getDao(CategoryDao.class).get(categoryId);
        if (category == null) {
            return this.renderError(404, response);
        } else {
            QueryResult qr = DaoFactory.getDao(DesignDao.class).getByCategory(1, categoryId);
            this.setAttr("category", category);
            this.setAttr("list", qr.getList());
            return this.render("/design/listByCategory.html");
        }
    }


    /**
     * 获取搜索列表
     */
    @RequestMapping(value = "listBySearch", method = RequestMethod.GET)
    public Object listBySearch(@RequestParam(value = "content", required = true) String content, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        QueryResult qr = DaoFactory.getDao(DesignDao.class).search(1, content);
        this.setAttr("list", qr.getList());
        this.setAttr("search", content);
        return this.render("/design/listBySearch.html");
    }


    /**
     * 拉取搜索列表(json返回)
     */
    @RequestMapping(value = "moreBySearch", method = RequestMethod.GET)
    @ResponseBody
    public Object moreBySearch(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "content", required = true) String content, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        List<Design> list = (List<Design>) (DaoFactory.getDao(DesignDao.class).search(page + 1, content)).getList();
        Map[] jsonList = new Map[list.size()];
        Map<String, Object> json = new HashMap<String, Object>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> imgJson = new HashMap<String, Object>();
            imgJson.put("shirtId", list.get(i).getId());
            imgJson.put("shirtSrc", "design?design=" + list.get(i).getId());
            imgJson.put("imgSrc", list.get(i).getName());
            imgJson.put("desc", list.get(i).getName());
            jsonList[i] = imgJson;
        }
        json.put("imgs", jsonList);
        return json;
    }


    /**
     * 获取热门列表
     */
    @RequestMapping(value = "listByHot", method = RequestMethod.GET)
    public Object listByHot(HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        QueryResult qr = DaoFactory.getDao(DesignDao.class).getByHot(1);
        this.setAttr("list", qr.getList());
        return this.render("/design/listByHot.html");
    }


    /**
     * 拉取热门列表(json返回)
     */
    @RequestMapping(value = "moreByHot", method = RequestMethod.GET)
    @ResponseBody
    public Object moreByHot(@RequestParam(value = "page", required = true) int page, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        List<Design> list = (List<Design>) (DaoFactory.getDao(DesignDao.class).getByHot(page + 1)).getList();
        Map[] jsonList = new Map[list.size()];
        Map<String, Object> json = new HashMap<String, Object>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> imgJson = new HashMap<String, Object>();
            imgJson.put("shirtId", list.get(i).getId());
            imgJson.put("shirtSrc", "design?design=" + list.get(i).getId());
            imgJson.put("imgSrc", list.get(i).getName());
            imgJson.put("desc", list.get(i).getName());
            jsonList[i] = imgJson;
        }
        json.put("imgs", jsonList);
        return json;
    }


    /**
     * 获取热门列表
     */
    @RequestMapping(value = "listByNew", method = RequestMethod.GET)
    public Object listByNew(HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        QueryResult qr = DaoFactory.getDao(DesignDao.class).getByNew(1);
        this.setAttr("list", qr.getList());
        return this.render("/design/listByNew.html");
    }


    /**
     * 拉取hot列表(json返回)
     */
    @RequestMapping(value = "moreByNew", method = RequestMethod.GET)
    @ResponseBody
    public Object moreByNew(@RequestParam(value = "page", required = true) int page, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        List<Design> list = (List<Design>) (DaoFactory.getDao(DesignDao.class).getByNew(page + 1)).getList();
        Map[] jsonList = new Map[list.size()];
        Map<String, Object> json = new HashMap<String, Object>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> imgJson = new HashMap<String, Object>();
            imgJson.put("shirtId", list.get(i).getId());
            imgJson.put("shirtSrc", "design?design=" + list.get(i).getId());
            imgJson.put("imgSrc", list.get(i).getName());
            imgJson.put("desc", list.get(i).getName());
            jsonList[i] = imgJson;
        }
        json.put("imgs", jsonList);
        return json;
    }


    /**
     * 拉取design列表(json返回)
     */
    @RequestMapping(value = "moreByCategory", method = RequestMethod.GET)
    @ResponseBody
    public Object moreByCategory(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "category", required = true) int categoryId, HttpServletResponse response, HttpServletRequest request) {
        clearAttr(request);
        DesignDao dao = DaoFactory.getDao(DesignDao.class);
        List<Design> list = (List<Design>) dao.getByCategory(page + 1, categoryId).getList();
        Map[] jsonList = new Map[list.size()];
        Map<String, Object> json = new HashMap<String, Object>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> imgJson = new HashMap<String, Object>();
            imgJson.put("shirtId", list.get(i).getId());
            imgJson.put("shirtSrc", "design?design=" + list.get(i).getId());
            imgJson.put("imgSrc", list.get(i).getName());
            imgJson.put("desc", list.get(i).getName());
            jsonList[i] = imgJson;
        }
        json.put("imgs", jsonList);
        return json;
    }


    /**
     * 根据sort获取更多
     */
    @RequestMapping(value = "moreBySort", method = RequestMethod.GET)
    @ResponseBody
    public Object moreBySort(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "sort", required = true) int sort, HttpServletResponse response, HttpServletRequest request) {
        clearAttr(request);
        DesignDao dao = DaoFactory.getDao(DesignDao.class);
        List<Design> list = (List<Design>) dao.getByCategory(page + 1, sort).getList();
        Map[] jsonList = new Map[list.size()];
        Map<String, Object> json = new HashMap<String, Object>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> imgJson = new HashMap<String, Object>();
            imgJson.put("shirtId", list.get(i).getId());
            imgJson.put("shirtSrc", "design?design=" + list.get(i).getId());
            imgJson.put("imgSrc", list.get(i).getName());
            imgJson.put("desc", list.get(i).getName());
            jsonList[i] = imgJson;
        }
        json.put("imgs", jsonList);
        return json;
    }


    /**
     * 添加评论
     */
    @RequestMapping(value = "addPost", method = RequestMethod.POST)
    public Object addPost(@RequestParam(value = "design", required = true) int design_id, @RequestParam(value = "content", required = true) String content, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        DesignDao designDao = DaoFactory.getDao(DesignDao.class);
        NoticeDao noticeDao = DaoFactory.getDao(NoticeDao.class);

        Design design = designDao.get(design_id);
        if (design == null) {
            return this.renderError(404, response);
        } else {
            noticeDao.addDesignMessageNotice(design.getId(), design.getUser().getId());
            User user = (User) request.getSession().getAttribute("user");
            designDao.newPost(design_id, user.getId(), design.getUser_id(), content);

            return this.redirect("/design?design=" + design.getId());
        }
    }


    /**
     * 确认订单
     */
    @RequestMapping(value = "conform", method = RequestMethod.POST)
    public Object conformOrder(HttpServletResponse response, HttpServletRequest request) {
        clearAttr(request);
        OrderForm form = new OrderForm(request);
        if (form.verify()) {
            User user = (User) request.getSession().getAttribute("user");
            DesignDao designDao = DaoFactory.getDao(DesignDao.class);
            Design design = designDao.get(form.getInt("design"));
            if (design == null) {
                return this.renderError(404, response);
            } else {
                Order order = new Order();

                order.setDesign_id(design.getId());
                order.setSize(form.getInt("size"));
                order.setCount(form.getInt("count"));
                order.setUser_id(user.getId());
                request.getSession().setAttribute("order", order);//添加session

                this.setAttr("design", design);
                this.setAttr("order", order);
                return this.render("/order/conform.html");
            }
        } else {
            return this.redirect("/design?design=" + form.getInt("design"));
        }
    }


    /**
     * 确认后提交订单
     *
     * @param design_id 订单的id
     */
    @RequestMapping(value = "addOrder", method = RequestMethod.POST)
    public Object makeOrder(@RequestParam(value = "design", required = true) int design_id, @RequestParam(value = "message", required = false) String message, HttpServletRequest request, HttpServletResponse response) {
        clearAttr(request);
        OrderDao orderDao = DaoFactory.getDao(OrderDao.class);

        Order order = (Order) request.getSession().getAttribute("order");
        if (order != null) {
            if (order.getDesign_id() == design_id) {
                order.setType(0);//设定交易状态
                order.setTime(new Date());//设定交易时间
                order.setMessage(message);
                if (orderDao.saveOrder(order)) {
                    DaoFactory.getDao(DesignDao.class).addCount(order.getDesign_id());
                    request.getSession().setAttribute("msg", "交易成功");
                    request.getSession().removeAttribute("order");

                    return this.redirect("/design/info?design=" + design_id);
                } else {
                    request.getSession().setAttribute("msg", "交易失败");
                    request.getSession().removeAttribute("order");
                    return this.redirect("/design/info?design=" + design_id);
                }
            } else {
                request.getSession().setAttribute("msg", "提交有误");
                request.getSession().removeAttribute("order");
                return this.redirect("/design/info?design=" + design_id);
            }
        } else {
            request.getSession().setAttribute("msg", "无订单信息");
            return this.redirect("/design/info?design=" + design_id);
        }
    }

}
